import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
// 临时解决方案：将接口内联或创建本地接口
// import { LogsService } from '../../logs/logs.service';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  // 暂时注释掉constructor，并修改实现
  // constructor(private readonly logsService: LogsService) {}

  use(req: Request, res: Response, next: NextFunction) {
    const { ip, method, path, body } = req;
    const userAgent = req.get('user-agent') || '';
    
    // 获取用户ID（需要从JWT中解析）
    const user = req['user'];
    const userId = user && 'userId' in user ? user.userId : null;
    
    // 保存请求开始时间
    const startTime = Date.now();
    
    // 响应完成后记录日志
    res.on('finish', () => {
      const { statusCode } = res;
      const responseTime = Date.now() - startTime;
      
      // 临时记录到控制台而不是数据库
      console.log({
        userId,
        method,
        path,
        params: body,
        statusCode,
        responseTime,
        ip,
        userAgent,
      });
    });
    
    next();
  }
} 